import random

from django.shortcuts import render
from django.http.response import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
# Create your views here.


class ImageCodeView(View):
    """图片验证码"""
    def get(self, request, uuid):
        # 1、获取前端uuid
        # this.image_code_url = this.host + "/image_codes/" + this.image_code_id + "/";
        # 2、生成图片验证码
        text, image = captcha.generate_captcha()
        # 3、保存图片验证码 （redis缓存）
        redis_cli = get_redis_connection('verifications_code')
        redis_cli.setex(uuid, 300, text)
        # 4、返回二进制数据   图片为bytes类型，指定content_type（MIME类型）
        return HttpResponse(content=image, content_type='image/jpeg')


class SmsCodeView(View):
    """短信验证码"""
    def get(self, request, mobile):
        # 1、获取前端数据  GET  mobile,image_code,image_code_id
        #   var url = this.host + '/sms_codes/' + this.mobile + '/' +
        #   '?image_code=' + this.image_code+ '&image_code_id=' + this.image_code_id
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')
        # 2、校验数据
        if not all([mobile, image_code, image_code_id]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        redis_cli = get_redis_connection('verifications_code')
        redis_pipeline = redis_cli.pipeline()      # 创建Redis管道
        # ===============================
        redis_image_code = redis_cli.get(image_code_id)
        redis_sms_flag = redis_cli.get('sms_flag_%s' % mobile)
        # Mind---------------------------
        # redis_pipeline.get(image_code_id)
        # redis_pipeline.get('sms_flag_%s' % mobile)
        # redis_image_code, redis_sms_flag = redis_pipeline.execute()
        # ===============================
        #   2.1、图片是否已失效
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': '图片验证码已失效'})
        #   2.2、验证码是否正确
        if image_code.lower() != redis_image_code.decode().lower():
            return JsonResponse({'code': 400, 'errmsg': '图片验证码输入有误'})
        #   2.3 防止频繁发送短信验证码
        if redis_sms_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'})
        sms_code = "%06d" % random.randint(1000, 999999)
        # ============3、生成并发送短信验证码======================
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # Mind-------------celery------------------------
        # from apps.verifications.tasks import send_sms_code
        # send_sms_code.delay(mobile, sms_code)  # Care delay()
        # =====================================================
        # ==========4、保存短信验证码=========================
        # redis_cli.setex(mobile, 300, sms_code)
        #     4.1、添加手机标记
        # redis_cli.setex('sms_flag_%s' % mobile, 300, 1)
        # Mind---------redis pipeline---------------------
        redis_pipeline.setex(mobile, 300, sms_code)
        #     4.1、添加手机标记
        redis_pipeline.setex('sms_flag_%s' % mobile, 300, 1)
        redis_pipeline.execute()
        # ==================================================
        # 5、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

